<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <div class="no-print">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('项目名称')">
              <template>
                <router-link
                  target="_blank"
                  :to="{path:'/deal/home/dealBaseHome',query:{id:form.dealId,companyId:form.companyId}}"
                  class="link_a"
                >{{ form.dealName }}
                </router-link>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('公司名称')">
              <template>
                <router-link
                  target="_blank"
                  :to="{path:'/company/base/companyBaseHome',query:{companyId:form.companyId}}"
                  class="link_a"
                >{{ form.companyName }}
                </router-link>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('申请标题')" prop="actTitle">
              <el-input v-model="form.actTitle" placeholder="请输入标题" show-word-limit :maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('聚焦行业')" prop="industryFocus">
              <FocusIndustry :industry-data="form.industryFocusList" @industryFocusList="getIndustryFocusList" />
            </el-form-item>
          </el-col>
        </el-row>
        <div>
          <div class="area-header mt10" style="position: unset;">
            <span class="area-header-title">{{ $t('团队成员') }}</span>
          </div>
          <el-table :data="form.dealTeamList" border class="nowrapTable formTable">
            <el-table-column :label="$t('序号')" align="center" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('用户名称')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('用户名称') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealTeamList.' + scope.$index + '.user.userId'" :rules="dealTeamListRules.user">
                  <UserSelect v-model="scope.row.user.userId" :placeholder="$t('用户名称')" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('参与角色')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('参与角色') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealTeamList.' + scope.$index + '.role'" :rules="dealTeamListRules.role">
                  <el-select v-model="scope.row.role" :placeholder="$t('参与角色')">
                    <el-option
                      v-for="dict in roleOptions"
                      :key="dict.dictValue"
                      :label="$t(dict.dictLabel)"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('参与时间')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('参与时间') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealTeamList.' + scope.$index + '.joinTime'" :rules="dealTeamListRules.joinTime">
                  <DatePicker
                    v-model="scope.row.joinTime"
                    :placeholder="$t('参与时间')"
                    @change="checkTime(scope.$index, 'joinTime')"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('是否离开')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('是否离开') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealTeamList.' + scope.$index + '.leave'" :rules="dealTeamListRules.leave">
                  <el-select
                    v-model="scope.row.leave"
                    :placeholder="$t('是否离开')"
                    @change="changeLeave(scope.$index)"
                  >
                    <el-option
                      v-for="dict in leaveOptions"
                      :key="dict.dictValue"
                      :label="$t(dict.dictLabel)"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('离开时间')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('离开时间') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealTeamList.' + scope.$index + '.leaveTime'" :rules="dealTeamListRules.leaveTime">
                  <DatePicker
                    v-model="scope.row.leaveTime"
                    :disabled="scope.row.leave === 'N'"
                    :placeholder="$t('离开时间')"
                    @change="checkTime(scope.$index, 'leaveTime')"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  icon="el-icon-delete"
                  @click="delHandle(scope.$index, scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
          <div v-if="!otherBtnHide" class="tol">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="addHandle">{{ $t('添加') }}</el-button>
          </div>
        </div>
        <FileTable :list.sync="form.fileList" data-type="deal_team_process" :business-id="form.dealId" :btn-show="!otherBtnHide" />
      </div>
      <div v-if="formList instanceof Array && formList.length > 0" id="print" ref="print" style="display:none;">
        <PageForm :form-list="formList" :model="form" />
      </div>
    </el-form>
  </div>
</template>

<script>
import { delDealTeamProcessDetails, getDealTeamProcess, saveDealTeamProcess } from '@/api/sass/syhk/dealTeamProcess'
import { listDealTeam } from '@/api/deal/team/dealTeam'
import { getDealBase } from '@/api/base/deal/dealBase'

export default {
  data() {
    const checkTimes = (rule, value, callback) => {
      const index = parseInt(rule.field.substring(rule.field.indexOf('.') + 1, rule.field.lastIndexOf('.')))
      if (this.form.dealTeamList[index].leave === 'Y') {
        if (this.isEmpty(this.form.dealTeamList[index].leaveTime)) {
          callback(new Error(this.$t('必填信息')))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      // 表单参数
      form: {
        dealTeamList: []
      },
      // 表单校验
      rules: {
        actTitle: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        industryFocus: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      dealTeamListRules: {
        user: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        role: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        joinTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        leave: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        leaveTime: [{ required: true, validator: checkTimes, trigger: 'blur' }]
      },
      roleOptions: [],
      leaveOptions: [],
      // 遮罩层
      loading: false,
      // 操作按钮默认不展示
      buttonShow: true,
      // 是否隐藏保存按钮
      otherBtnHide: false,
      formList: []
    }
  },
  created() {
    this.$bus.$emit('async_done')
    this.getDicts('deal_team_role').then(response => {
      this.roleOptions = response.data
    })
    this.getDicts('sys_yes_no').then(response => {
      this.leaveOptions = response.data
    })
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        getDealTeamProcess(data.id).then(response => {
          this.form = response.data
          this.loading = false
          this.loadForm()
        })
      } else {
        this.reset()
        this.form.actTitle = !this.isEmpty(data) ? data.actTitle : ''
        if (!this.isEmpty(data)) {
          // 默认带出流程中必须要传的附件
          this.form.fileList = this.isEmpty(data.fileList) ? [] : data.fileList
        }
        // 获取当前项目的dealId
        listDealTeam({ dealId: this.$route.query.id }).then(response => {
          this.form.dealTeamList = []
          response.rows && response.rows.forEach(item => {
            item.id = undefined
            this.form.dealTeamList.push(item)
          })
          getDealBase(this.$route.query.id).then(deal => {
            this.loading = false
            this.form.dealName = deal.data.dealName
            this.form.companyName = deal.data.company.companyName
            this.form.companyId = deal.data.company.id
          })
        })
      }
    },
    loadForm() {
      this.$nextTick(() => {
        this.formList = [
          { title: '申请单', value: 'input', type: 'table',
            tablePageList: [
              { title: '项目名称', type: 'title' },
              { title: '项目名称', value: 'dealName', type: 'textarea' },
              { title: '公司名称', type: 'title' },
              { title: '公司名称', value: 'companyName', type: 'textarea' },
              { title: '申请标题', type: 'title' },
              { title: '申请标题', value: 'actTitle', type: 'textarea', width: '75%' },
              { title: '聚焦行业', type: 'title' },
              { title: '聚焦行业', value: 'industryFocusList', type: 'FocusIndustry', width: '75%' }
            ]
          },
          { title: '团队成员', value: 'dealTeamList', type: 'dataList', listType: 'vertical',
            vIf: this.form.dealTeamList.length > 0,
            listPageList: [
              { title: '用户名称', value: 'user', childrenValue: 'nickName' },
              { title: '参与角色', value: 'role', type: 'select', selectType: 'options', selectDataList: this.roleOptions, selectLabelParams: 'dictLabel', selectValueParams: 'dictValue' },
              { title: '参与时间', value: 'joinTime', type: 'time' },
              { title: '是否离开', value: 'leave', type: 'select', selectType: 'options', selectDataList: this.leaveOptions, selectLabelParams: 'dictLabel', selectValueParams: 'dictValue' },
              { title: '离开时间', value: 'leaveTime', type: 'time' }
            ]
          },
          { title: '附件信息', value: 'fileList', type: 'fileList', listType: 'vertical',
            vIf: this.form.fileList.length > 0,
            listPageList: [
              { title: '文件分类', value: 'directoryName' },
              { title: '附件名称', value: 'name' },
              { title: '备注', value: 'remark' },
              { title: '上传人', value: 'updateBy', childrenValue: 'nickName' },
              { title: '上传时间', value: 'createTime' }
            ]
          }
        ]
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        dealId: this.$route.query.id,
        actTitle: undefined,
        dealTeamList: [],
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        fileList: []
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    /** 提交按钮 */
    submitForm(type) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          // 验证数据
          if (valid) {
            // 弹出遮罩层
            this.loading = true
            // 保存数据
            saveDealTeamProcess(this.form).then(response => {
              if (response.code === 200) {
                if (type === 'process') {
                  this.startProcess(response.data)
                } else {
                  this.msgSuccess(this.$t('保存成功'))
                  this.loading = false
                  resolve(response.data.id)
                }
              } else {
                this.msgError(response.msg)
                this.loading = false
                reject(response)
              }
            }).catch(() => {
              this.loading = false
            })
          } else {
            reject()
            this.locationError(document)
          }
        })
      })
    },
    startProcess(data) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.form.actTitle
      // 业务表名
      processData.dataTable = this.$t('deal_team_process')
      // 业务ID
      processData.dataId = data.id
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = '@/views/saas/syhk/dealTeamProcessForm'
      processData.viewPath = '@/views/saas/syhk/dealTeamProcessForm'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = 'deal_team_process'
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
      })
    },
    addHandle() {
      const row = {
        id: undefined,
        user: {
          userId: ''
        },
        dealId: this.$route.query.id ? this.$route.query.id : this.form.dealId,
        role: undefined,
        joinTime: new Date(),
        leave: 'N',
        leaveTime: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      }
      if (!(this.form.dealTeamList instanceof Array)) {
        this.$set(this.form, 'dealTeamList', [])
      }
      this.$nextTick(() => {
        this.form.dealTeamList.push(row)
      })
    },
    delHandle(index, row) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(() => {
          return delDealTeamProcessDetails(id)
        }).then(() => {
          this.form.dealTeamList.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        })
      } else {
        this.form.dealTeamList.splice(index, 1)
      }
    },
    changeLeave(index) {
      if (this.form.dealTeamList[index].leave === 'N') {
        this.form.dealTeamList[index].leaveTime = undefined
      }
    },
    // 获取聚焦行业数据
    getIndustryFocusList(val) {
      this.form.industryFocus = val[0]
      if (val[1]) {
        this.form.industryFocusTwo = val[1]
      } else {
        this.form.industryFocusTwo = ''
      }
    },
    checkTime(index, field) {
      var start = this.form.dealTeamList[index].joinTime
      var end = this.form.dealTeamList[index].leaveTime
      if (start && end) {
        if (new Date(start).getTime() >= new Date(end).getTime()) {
          this.form.dealTeamList[index][field] = undefined
          this.msgError(this.$t('不能早于参与时间'))
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .el-popper.el-select-dropdown {
  position: fixed !important;
}
</style>
